//
//  SearchViewController.m
//  customer
//
//  Created by 往返网络 on 17/8/24.
//  Copyright © 2017年 com. All rights reserved.
//

#import "SearchViewController.h" //搜索页面id号
#import "SearchListViewController.h" //搜索列表页
#import "PublicMethod.h"
//定义搜索URL
#define URL_SEARCH [NSString stringWithFormat:@"%@/Appcustomernewer/Order/searchOrder?type=get",BASE_URL]
@interface SearchViewController ()<UISearchBarDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UIView * searchview;
@property (nonatomic,strong)UITextField * searchbartf1;
@property (nonatomic,strong)NSMutableArray * resultArray; //结果数据源
@property (nonatomic,strong)NSMutableArray * dataSource;  //总数据源
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@property (nonatomic,strong)NSMutableDictionary * docu_data; //运单数据

@end

@implementation SearchViewController
{
    UISearchBar * searchbar;
    
    UITableView * tableview;

}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    // Do any additional setup after loading the view.
}

- (void)loadData{
    //请求数据源
    [self.dataSource removeAllObjects];
   
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    //去除空格和换行
   NSString * searchstring = [_searchbartf1.text stringByReplacingOccurrencesOfString: @" " withString: @""];
    searchstring = [searchstring stringByReplacingOccurrencesOfString: @"\n" withString: @""];

    NSString * url = [NSString stringWithFormat:@"%@&token=%@&ordersn=%@",URL_SEARCH,token,searchstring];
    NSString * URL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"search url %@",url);
    //播放动画
    UIImageView * im = [PublicMethod startAnimation];

    [self.manger GET:URL parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                // 停止动画
                [im stopAnimating];
                _docu_data = [NSMutableDictionary dictionaryWithDictionary:dict[@"data"]];
                NSString * result = _searchbartf1.text;
                self.resultArray = [NSMutableArray arrayWithObject:result];
                [tableview reloadData];
                
            }else{
                
                [im stopAnimating];
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
        [im stopAnimating];
        
    }];

    
    
    
    
    
}
- (void)createUI{
    
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    //设置表头
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    _searchview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    _searchview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:_searchview];
    
    
    float cornersizeSearch = 15; //searchbar的圆角大小
    
    UIFont * iconfont = [UIFont fontWithName:@"iconfont" size:fontsize];
    
    cornersizeSearch = SCREEN_H < 667 ? 13 : 16 ;
    
    fontsize = SCREEN_H < 667 ? 12 : 16 ;
    
    if (SCREEN_H == 667) {
        
        iconfont = [UIFont fontWithName:@"iconfont" size:18];
        
        fontsize = 14;
        
        cornersizeSearch = 15;
        
    }
    
    _searchbartf1 = [[UITextField alloc]initWithFrame:CGRectMake(20.0/W_BASE*SCREEN_W, 20+14.0/1334*SCREEN_H, 600.0/W_BASE*SCREEN_W, 60.0/1334*SCREEN_H)];
    
    _searchbartf1.backgroundColor = [UIColor whiteColor];
    
    _searchbartf1.placeholder = @"搜索运单编号";
    
    _searchbartf1.layer.cornerRadius = cornersizeSearch;
    
    _searchbartf1.layer.borderColor = [[UIColor whiteColor]CGColor];
    
    _searchbartf1.layer.borderWidth = 1;
    
    _searchbartf1.delegate = self;
    
    _searchbartf1.clipsToBounds = YES;
    _searchbartf1.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchbartf1.returnKeyType=UIReturnKeySearch;
    //设置tf中placeholder的字体颜色
    
    [_searchbartf1 setValue:COLORRGBA(153, 153, 153, 1)  forKeyPath:@"_placeholderLabel.textColor"];
    
    _searchbartf1.font = [UIFont systemFontOfSize:fontsize];
    
    [_searchview addSubview:_searchbartf1];
    
    
    UIButton * leftbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80.0/750*SCREEN_W , 70.0/1334*SCREEN_H)];
    
    leftbtn.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize+2];
    
    [leftbtn setTitle:@"\U0000e6ac" forState:UIControlStateNormal];
    
    [leftbtn setTitleColor:COLORRGBA(153, 153, 153, 1) forState:UIControlStateNormal];
    
    _searchbartf1.leftView = leftbtn;
    
    _searchbartf1.leftViewMode = UITextFieldViewModeAlways;
    
    //取消按钮
    UIButton * cancelbtn  = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W- 100.0/W_BASE*SCREEN_W, 20+14.0/1334*SCREEN_H, 80.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    
    [cancelbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    cancelbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize+3];
    
    [cancelbtn setTitle:@"取消" forState:UIControlStateNormal];
    
    [cancelbtn.titleLabel setTextAlignment:NSTextAlignmentCenter];
    
    [cancelbtn addTarget:self action:@selector(returnLast) forControlEvents:UIControlEventTouchUpInside];
    
    [_searchview addSubview:cancelbtn];
    
    tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, SCREEN_H-64) style:UITableViewStylePlain];
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    tableview.rowHeight = 44;
    
    tableview.delegate = self;
    
    tableview.dataSource = self;
    tableview.backgroundColor = COLORRGBA(239, 239, 239, 1);
    
    [self.view addSubview:tableview];

    
}

#pragma mark -- Tableview-Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.resultArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }

    UITableViewCell * cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    cell.textLabel.text  = self.resultArray[indexPath.row];
    cell.textLabel.textColor = COLORRGBA(153, 153, 153, 1);
    cell.textLabel.font  = [UIFont systemFontOfSize:fontsize-3];
    cell.backgroundColor  = [UIColor whiteColor];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchListViewController * searchvc = [[SearchListViewController alloc]init];
//    searchvc.id =   //获取运单id号
    searchvc.doucu_string = self.resultArray[indexPath.row];
    [self.navigationController pushViewController:searchvc animated:YES];

}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    
//    //不断输入，不断查询请求数据源
//    
//    [self.resultArray removeAllObjects];
//    //加个多线程，否则数量量大的时候，有明显的卡顿现象
//    //这里最好放在数据库里面再进行搜索，效率会更快一些
//    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
//    dispatch_async(globalQueue, ^{
//        
//        if (_searchbartf1.text!=nil && _searchbartf1.text.length>0) {
//            
//            //遍历需要搜索的所有内容，其中self.dataArray为存放总数据的数组
//            
//                for (int i = 0; i< self.dataSource.count; i++) {
//                    
//                    NSString *tempStr = self.dataSource[i];
//                    
//                    NSString *pinyin = [self transformToPinyin:tempStr];
//                    
//                    
//                    if ([pinyin rangeOfString:_searchbartf1.text options:NSCaseInsensitiveSearch].length >0 ) {
//                        
//                        [self.resultArray addObject:tempStr];
//                    }
//                    
//                }
//        }
//                
//        //回到主线程
//        dispatch_async(dispatch_get_main_queue(), ^{
//            
//            [tableview reloadData];
//            
//        });
//        
//    });
//   
//    return YES;
//
//}

- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    int count = 0;
    
    for (int  i = 0; i < pinyinArray.count; i++)
    {
        
        for(int i = 0; i < pinyinArray.count;i++)
        {
            if (i == count) {
                [allString appendString:@"#"];//区分第几个字母
            }
            [allString appendFormat:@"%@",pinyinArray[i]];
            
        }
        [allString appendString:@","];
        count ++;
        
    }
    
    NSMutableString *initialStr = [NSMutableString new];//拼音首字母
    
    for (NSString *s in pinyinArray)
    {
        if (s.length > 0)
        {
            
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    
    return allString;
}

- (void)returnLast{
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.view endEditing:YES];
    [self loadData]; //请求数据
    return YES;
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}

- (NSMutableArray *)resultArray{

    if (!_resultArray) {
        _resultArray  = [NSMutableArray array];
    }
    return _resultArray;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - - -- - - - 懒加载 ---- - -- - -

- (AFHTTPSessionManager*)manger{
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
        
    }
    
    return _manger;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
